package blog.controller;


import blog.entity.Consumer;
import blog.service.back.ConsumerBackService;
import blog.util.back.ControllerUtil;
import blog.util.back.EmailUtil;
import blog.vo.back.*;
import blog.vo.common.PaginationVO;
import blog.vo.common.ResponseListObjectVO;
import blog.vo.common.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 　　* @description: TODO
 * 　　* @param
 * 　　* @return
 * 　　* @throws
 * 　　* @author Administrator
 * 　　* @date $ $
 */
@Controller
@RequestMapping("/user")
public class ConsumerController {
    @Autowired
    private ConsumerBackService consumerBackService;

    private Consumer consumer;

    @PostMapping("/login")
    public String login(String phoneNumberOrEmail, String consumerPassword, Model model, HttpSession session) {
        if (phoneNumberOrEmail.contains("@qq.com")) {
            consumer = consumerBackService.emailLogin(new EmailLoginVO(phoneNumberOrEmail, consumerPassword));
        }
        else {
            consumer = consumerBackService.phoneNumberLogin(new PhoneNumberLoginVO(phoneNumberOrEmail, consumerPassword));
        }
        if (consumer == null) {
            model.addAttribute("consumer", new ResponseVO<Consumer>(1001, "账号或者密码错误", null));
            return "error-login";
        }
        if (consumer.getConsumerRoot() != 2) {
            model.addAttribute("consumer", new ResponseVO<Consumer>(1001, "你的权限不足", null));
            return "error-login";
        } else {
            session.setAttribute("consumer", new ResponseVO<Consumer>(200, "ok", consumer));
            session.setMaxInactiveInterval(3600);
            List<Consumer> allConsumer = consumerBackService.getAllConsumer(new PaginationVO());
            model.addAttribute("allConsumer", new ResponseListObjectVO<Consumer>(200, "ok", allConsumer).getResponseObject());
        }
        return "home";
    }

    @GetMapping("/exit-login")
    public String exitLogin( HttpSession session) {
        session.setAttribute("consumer","");
        return "login";
    }

    @RequestMapping("/consumer-add")
    public String consumerAdd() {
        return "consumer-add";
    }

    @RequestMapping("/get-all-consumer")
    public String getAllConsumer(PaginationVO paginationVO, Model model) {
        List<Consumer> allConsumer = consumerBackService.getAllConsumer(paginationVO);
        model.addAttribute("allConsumer", new ResponseListObjectVO<Consumer>(200, "ok", allConsumer).getResponseObject());
        return "home";
    }

    @PostMapping("/by-consumer-root-get-consumerInfo")
    public String byConsumerRootGetConsumerInfo(ByConsumerRootGetConsumerInfoVO byConsumerRootGetConsumerInfoVO, Model model, HttpSession session) {
        List<Consumer> consumers = consumerBackService.byConsumerRootGetConsumerInfo(byConsumerRootGetConsumerInfoVO);
        session.setAttribute("consumerRoot", byConsumerRootGetConsumerInfoVO.getConsumerRoot());
        model.addAttribute("allConsumer", new ResponseListObjectVO<Consumer>(200, "ok", consumers).getResponseObject());
        return "home";
    }

    @PostMapping("/by-consumer-root-and-consumer-status-get-consumerInfo")
    public String byConsumerRootAndConsumerStatusGetConsumerInfo(ByConsumerRootAndConsumerStatusGetConsumerInfoVO byConsumerRootAndConsumerStatusGetConsumerInfoVO, Model model, HttpSession session) {
        Integer consumerRoot = (Integer) session.getAttribute("consumerRoot");
        byConsumerRootAndConsumerStatusGetConsumerInfoVO.setConsumerRoot(consumerRoot);
        List<Consumer> consumers = consumerBackService.byConsumerRootAndConsumerStatusGetConsumerInfo(byConsumerRootAndConsumerStatusGetConsumerInfoVO);
        model.addAttribute("allConsumer", new ResponseListObjectVO<Consumer>(200, "ok", consumers).getResponseObject());
        return "home";
    }

    @PostMapping("/by-consumer-name-get-consumerInfo")
    public String byConsumerNameGetConsumerInfo(ByConsumerNameGetConsumerInfoVO byConsumerNameGetConsumerInfoVO, Model model) {
        if (byConsumerNameGetConsumerInfoVO.getConsumerName() == null || byConsumerNameGetConsumerInfoVO.getConsumerName() == ""){
            return "redirect:/user/get-all-consumer";
        }
        List<Consumer> consumers = consumerBackService.byConsumerNameGetConsumerInfo(byConsumerNameGetConsumerInfoVO);
        model.addAttribute("allConsumer", new ResponseListObjectVO<Consumer>(200, "ok", consumers).getResponseObject());
        return "home";
    }

    @RequestMapping("/by-consumer-uuid-get-consumerInfo")
    public String byConsumerUuidGetConsumerInfo(ByConsumerUuidGetConsumerInfoVO byConsumerUuidGetConsumerInfoVO, Model model, RedirectAttributes attributes) {
        String consumerUuid = (String) attributes.getAttribute("consumerUuid");
        if (consumerUuid != null && consumerUuid != "") {
            byConsumerUuidGetConsumerInfoVO.setConsumerUuid(consumerUuid);
            Consumer consumer = consumerBackService.byConsumerUuidGetConsumerInfo(byConsumerUuidGetConsumerInfoVO);
            model.addAttribute("consumer", new ResponseVO<Consumer>(200, "ok", consumer).getResponseObject());
        } else {
            Consumer consumer = consumerBackService.byConsumerUuidGetConsumerInfo(byConsumerUuidGetConsumerInfoVO);
            model.addAttribute("consumer", new ResponseVO<Consumer>(200, "ok", consumer).getResponseObject());
        }
        return "consumer";
    }

    @PostMapping("/update-consumerInfo")
    public String updateConsumerInfo(UpdateConsumerInfoVO updateConsumerInfoVO, Model model) {
        if (EmailUtil.isEmail(updateConsumerInfoVO.getConsumerEmail()) == false){
            model.addAttribute("error",new ResponseVO<Consumer>(500,"邮箱格式不一致",null));
            return "error";
        }
        if (updateConsumerInfoVO.getPhoneNumber().length() < 11 || updateConsumerInfoVO.getPhoneNumber().length() > 11){
            model.addAttribute("error",new ResponseVO<Consumer>(500,"手机号码错误",null));
            return "error";
        }
        if (updateConsumerInfoVO.getConsumerPassword().length() < 16 || updateConsumerInfoVO.getConsumerPassword().length() > 26){
            model.addAttribute("error",new ResponseVO<Consumer>(500,"密码小于16或者大于16",null));
            return "error";
        }
        String consumerName = replaceContent(updateConsumerInfoVO.getConsumerName());
        updateConsumerInfoVO.setConsumerName(consumerName);

        int result = consumerBackService.updateConsumerInfo(updateConsumerInfoVO);
        String resultUrl = ControllerUtil.updateResultUrl(result, "redirect:/user/get-all-consumer", model);
        return resultUrl;
    }

    @PostMapping("/add-root-consumer")
    public String addRootConsumer(AddRootConsumerVO addRootConsumerVO, Model model,HttpSession session) {
        if (addRootConsumerVO.getConsumerEmail()==""||addRootConsumerVO.getConsumerName()==""||addRootConsumerVO.getConsumerPassword()==""||addRootConsumerVO.getPhoneNumber()==""){
            String addResultUrl = ControllerUtil.addResultUrl(0, "redirect:/user/get-all-consumer", model);
            return addResultUrl;
        }
        boolean email = EmailUtil.isEmail(addRootConsumerVO.getConsumerEmail());
        if (email == false){
            model.addAttribute("error",new ResponseVO<Consumer>(500,"邮箱格式不一致",null));
            return "error";
        }
        if (addRootConsumerVO.getPhoneNumber().length() < 11 || addRootConsumerVO.getPhoneNumber().length() > 11){
            model.addAttribute("error",new ResponseVO<Consumer>(500,"手机号码错误",null));
            return "error";
        }
        if (addRootConsumerVO.getConsumerPassword().length() < 16 || addRootConsumerVO.getConsumerPassword().length() > 26){
            model.addAttribute("error",new ResponseVO<Consumer>(500,"密码小于16或者大于16",null));
            return "error";
        }
        String consumerHeadPortrait = (String) session.getAttribute("consumerHeadPortrait");
        if (consumerHeadPortrait != null && consumerHeadPortrait != "") {
            session.setMaxInactiveInterval(60);
            addRootConsumerVO.setConsumerHeadPortrait(consumerHeadPortrait);
        }
        String consumerName = replaceContent(addRootConsumerVO.getConsumerName());
        addRootConsumerVO.setConsumerName(consumerName);

        int result = consumerBackService.addRootConsumer(addRootConsumerVO);
        String addResultUrl = ControllerUtil.addResultUrl(result, "redirect:/user/get-all-consumer", model);
        return addResultUrl;
    }

    @PostMapping("/add-consumer-headPortrait")
    public String addConsumerHeadPortrait(MultipartFile myFile, HttpSession session) {
        try {
            String courseFile =  "C:\\Users\\Administrator\\IdeaProjects\\blog\\blog-back-controller\\target\\classes\\public\\consumer-head\\";
            Path path = Paths.get(courseFile, myFile.getOriginalFilename());
            myFile.transferTo(path);
            session.setAttribute("consumerHeadPortrait", "/static/consumer-head/" + myFile.getOriginalFilename());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return "redirect:consumer-add";
    }

    @PostMapping("/update-consumer-headPortrait")
    public String updateConsumerHeadPortrait(MultipartFile myFile, UpdateConsumerHeadPortraitVO updateConsumerHeadPortraitVO, RedirectAttributes attributes, Model model) {
        try {
            String courseFile =  "C:\\Users\\Administrator\\IdeaProjects\\blog\\blog-back-controller\\target\\classes\\public\\consumer-head\\";
            Path path = Paths.get(courseFile, myFile.getOriginalFilename());
            myFile.transferTo(path);

            updateConsumerHeadPortraitVO.setConsumerHeadPortrait("/static/consumer-head/" + myFile.getOriginalFilename());
            int result = consumerBackService.updateConsumerHeadPortrait(updateConsumerHeadPortraitVO);
            ControllerUtil.updateResultUrl(result, "redirect:/user/by-consumer-uuid-get-consumerInfo", model);

            attributes.addAttribute("consumerUuid", updateConsumerHeadPortraitVO.getConsumerUuid());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return "redirect:/user/by-consumer-uuid-get-consumerInfo";
    }

    private String replaceContent(String content) {
        InputStream inputStream = ConsumerController.class.getClassLoader().getResourceAsStream("mg.properties");
        String newContent = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String[] split = br.readLine().split(",");
            for (int i = 0; i < split.length; i++) {
                Pattern r = Pattern.compile(split[i]);
                Matcher m = r.matcher(content);
                if (m.find()) {
                    newContent += m.replaceAll("*");
                }
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return newContent;
    }
}
